import { Component, Host, ViewChild } from "@angular/core";
import { AppComponent } from "../../../../app/app.component";
import { FtpReportsService } from "../ftpReports.service";
import { ToasterService } from "angular2-toaster";
import { AccountsService } from "../../userManagement/accounts/accounts.service";
import { AccountModel } from "../../userManagement/accounts/models/accounts.model";
import { forkJoin } from "rxjs";
import { AccountInfoModel, FtpServerTypeEnum } from "../models/accountInfo.model";
import { ColumnOptions, ColumnType } from "../../../shared/components/table/models/columnOptions.model";
import { PaginationPositionDisplayEnum, TableComponent } from "../../../shared/components/table/table.component";
import { TableButton, ButtonType } from "../../../shared/components/table/models/tableButton.model";
import { FrequencyEnum, ClientReportModel } from "../models/clientReport.model";
import swal, { SweetAlertOptions } from "sweetalert2";

@Component({
    templateUrl: 'accountReports.component.html',
    styleUrls: ['../../../shared/components/table/table.component.scss']
})
export class AccountReportsComponent {
    private reportsArray: ClientReportModel[];
    private prevReport: ClientReportModel;
    private prevAccountInfo: AccountInfoModel;

    public accounts: AccountModel[];
    public selectedAccount: string = undefined;;
    public edit: boolean = false;
    public filters: any[];
    public accountInfo: AccountInfoModel;
    public reports: any[];
    public count: number;
    public paginationPosition = PaginationPositionDisplayEnum.UpAndDown;
    public report: ClientReportModel;

    public ftpTypes: typeof FtpServerTypeEnum = FtpServerTypeEnum;
    public frequencyEnum: typeof FrequencyEnum = FrequencyEnum;
    public editReport: boolean = false;
    public add: boolean = false;

    @ViewChild('reportsTable') reportsTable: TableComponent;

    public columns: ColumnOptions[] = [
        new ColumnOptions('reports', 'Existing Reports/filters', 'col-md-5', false, ColumnType.Label),
        new ColumnOptions('recurrence', 'Recurrence', 'col-md-2', false, ColumnType.Label),
        new ColumnOptions('generation', 'Generation Date', 'col-md-2', false, ColumnType.DateTime),
        new ColumnOptions('action', 'Actions', 'col-md-3', false, ColumnType.Buttons)
    ];

    constructor(@Host() private rootComponent: AppComponent,
        private ftpService: FtpReportsService,
        private accountsService: AccountsService,
        private toasterService: ToasterService) {
    }

    ngOnInit() {
        this.accountsService.getAccountsList('', '', 0, 5000).subscribe(data => {
            this.accounts = data;
            this.rootComponent.finishLoading();
        });
    }

    public accountSelected() {
        forkJoin([
            this.ftpService.getAdminFilters(this.selectedAccount),
            this.ftpService.getFtpAccountInfo(this.selectedAccount),
            this.ftpService.getFtpClientReport(this.selectedAccount)
        ]).subscribe(data => {            
            this.filters = data[0];
            this.accountInfo = data[1] != null ? data[1] : new AccountInfoModel(this.selectedAccount);
            this.reportsArray = data[2] != null ? data[2] : [];
            this.reports = this.reportsArray.map(report => {
                return {
                    reports: this.filters.find(x => x.id == report.reportId).name,
                    recurrence: FrequencyEnum[report.frequency],
                    generation: new Date(report.nextGenerationDate),
                    action: [
                        new TableButton('edit', { id: report.id, edit: true }, true, ButtonType.Button),
                        new TableButton('delete', { id: report.id, edit: false }, true, ButtonType.Button)
                    ]
                }
            });
            this.count = this.reports != null ? this.reports.length : 0;
        });
    }

    public editAccount() {
        this.prevAccountInfo = Object.assign({}, this.accountInfo);
        this.edit = true;
    }

    public cancel() {
        this.accountInfo = this.prevAccountInfo;
        this.edit = false;
    }

    public save() {
        this.edit = false;
        this.ftpService.saveAccountInfo(this.accountInfo).subscribe(_ => {
            this.toasterService.pop('success', 'Success', 'Save FTP Server settings succeeded');
        }, _ => {
            this.toasterService.pop('warning', 'Warning', 'The save operation failed. Possible reasons: invalid FTP address, FTP server timeout or access denied. Please ensure that the FTP server settings are valid for the target machine');
        });
    }

    public addReport() {
        this.report = new ClientReportModel();
        this.add = true;
        this.editReport = false;
    }

    public saveReport() {
        if (this.add == true) {
            this.report.accountId = this.selectedAccount;
            this.report.id = "00000000-0000-0000-1111-000000000000";
        }
        this.ftpService.saveReport(this.report, this.editReport).subscribe(_ => {
            this.toasterService.pop('success', 'Success', 'Save FTP Report succeeded');            
            if(this.add == true)
            {
                this.reportsArray.push(this.report);
                this.reports.push({
                    reports: this.filters.find(x => x.id == this.report.reportId).name,
                    recurrence: FrequencyEnum[this.report.frequency],
                    generation: new Date(),
                    action: [
                        new TableButton('edit', { id: this.report.reportId, edit: true }, true, ButtonType.Button),
                        new TableButton('delete', { id: this.report.reportId, edit: false }, true, ButtonType.Button)
                    ]
                });
            } else {
                let index = this.reportsArray.findIndex(x => x.id == this.report.id);
                this.reportsArray[index] = this.report;
                this.reports[index].reports = this.filters.find(x => x.id == this.report.reportId).name,
                this.reports[index].recurrence = FrequencyEnum[this.report.frequency];
            }
            this.reportsTable.updateSource(this.reports);
            this.add = false;
            this.editReport = false;
        });
    }

    public cancelChanges() {
        this.report = this.prevReport;
        this.add = false;
        this.editReport = false;
    }

    public onButtonClicked(event: any) {
        if (event.edit == true) {
            this.editReport = true;
            this.report = Object.assign({}, this.reportsArray.find(x => x.id == event.id));
            this.prevReport = Object.assign({}, this.report);
        }
        else {
            const swalOptions: SweetAlertOptions = {
                buttonsStyling: false,
                customClass: 'modal-content',
                showCancelButton: true,
                title: 'Delete Report',
                text: 'Ar you sure you want to delete this FTP Report?',
                confirmButtonClass: 'btn btn-primary',
                confirmButtonText: 'Delete',
                cancelButtonClass: 'btn btn btn-outline-dark-grey'
            };

            swal(swalOptions).then(result => {
                if (result && result.value) {
                    this.ftpService.deleteReport(this.selectedAccount, event.id).subscribe(_ => {
                        this.toasterService.pop('success', 'Success', 'Delete operation succeeded'); 
                        let index = this.reportsArray.findIndex(x => x.id == event.id);
                        this.reportsArray.splice(index, 1);
                        this.reports.splice(index, 1);
                        this.reportsTable.updateSource(this.reports);
                    });
                }
            });
        }
    }
}